/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ActivityLogFrame.java
 *
 * Created on Jan 31, 2012, 7:08:31 PM
 */
package gui;

import db.DatabaseManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.SpinnerDateModel;
import javax.swing.table.DefaultTableModel;

import excelexporter.ActivityBean;
import excelexporter.ExcelExporter;
import util.ErrorMessage;

/**
 *
 * @author suzann
 */
public class ActivityLogFrame extends javax.swing.JFrame {

    /** Creates new form ActivityLogFrame */
    public ActivityLogFrame() {
        initComponents();
        setInitData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jdcFrom = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        jdcTo = new com.toedter.calendar.JDateChooser();
        jbtDisplay = new javax.swing.JButton();
        jbtSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Action", "Time", "User ID", "Comments"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("From");

        jLabel2.setText("To");

        jbtDisplay.setText("Display");
        jbtDisplay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDisplayActionPerformed(evt);
            }
        });

        jbtSave.setText("Save");
        jbtSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jdcTo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jdcFrom, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtDisplay)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtSave)
                .addContainerGap(618, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jdcFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtDisplay)
                            .addComponent(jbtSave))
                        .addComponent(jdcTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 959, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-995)/2, (screenSize.height-698)/2, 995, 698);
    }// </editor-fold>
    /****************************************************************************
     * Action Listeners
     ****************************************************************************/
    private void jbtDisplayActionPerformed(java.awt.event.ActionEvent evt) {                                           
        showActivity();
    }                                          

    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {
        saveLog();
    }
    
    
    /****************************************************************************
     * Internal Operations
     ****************************************************************************/
    /**
     * This method sets the initial data for Tend Chart Display at first launch.
     * @param 
     */
    private void setInitData()
    {
        //default value for Date
        Calendar today = Calendar.getInstance();
        
        Calendar yesterday = Calendar.getInstance();
        yesterday.setTimeInMillis(today.getTimeInMillis() - 86400000L);
        
        this.jdcTo.setDate(today.getTime());
        this.jdcFrom.setDate(yesterday.getTime());
        
        //Variables initialisation
        dm = new db.DatabaseManager();        
    }
    private void showActivity()
    {
        if(! validateInput())
            return ;
        
    	Calendar fromDate = Calendar.getInstance();
    	fromDate.setTime(jdcFrom.getDate());
    	Date startDate = fromDate.getTime();
    	
    	Calendar toDate = Calendar.getInstance();
    	fromDate.setTime(jdcTo.getDate());
    	Date endDate = fromDate.getTime();
    	
    	DatabaseManager db = new DatabaseManager();
    	List<db.entity.Activitylog> activityLS = db.listActivityLog(startDate, endDate);
    	int row = activityLS.size();
    	
    	Object[][] tableData = new Object[row][4];
    	for(int i=0; i<row; i++)
    	{
    		db.entity.Activitylog actItem = activityLS.get(i);
    		tableData[i][0] = actItem.getId().getAction();
    		tableData[i][1] = actItem.getId().getTime();
    		tableData[i][2] = actItem.getUserID();
    		tableData[i][3] = actItem.getComment();    		
    	}
    	String [] columeNames = new String [] {
                "Action", "Time", "User ID", "Comments"
            };
    	
    	DefaultTableModel tableModel = new DefaultTableModel(tableData, columeNames);
    	jTable1.setModel(tableModel);
    	
    	invalidate();
    	validate();
    }
    private boolean validateInput()
    {    	
    	// VALIDATE BLANK FIELDS
    	boolean blankField = false;
    	String blankField_str = "";
    	if(jdcFrom.getDate()==null)
    	{
    		blankField_str += "jdcFromDate;";
    		blankField = true;
    	}    	
    	if(jdcTo.getDate()==null)
    	{
    		blankField_str += "jdcToDate;";
    		blankField = true;
    	}    	
    	
    	if(blankField)
    	{
    		String errMsg = "Please fill in the following field: \n" + blankField_str;
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	// VALIDATE FROM DATE BEFORE TO DATE
    	Date fromDate = jdcFrom.getDate();
    	Date toDate = jdcTo.getDate();
		
    	if(! fromDate.before(toDate))
    	{
    		String errMsg = "From Date should be a date before To Date.";
    		ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errMsg);
    		return false;
    	}
    	
    	return true;
    }
    private void saveLog()
    {
    	if(! validateInput())
            return ;
        
    	Calendar fromDate = Calendar.getInstance();
    	fromDate.setTime(jdcFrom.getDate());
    	Date startDate = fromDate.getTime();
    	
    	Calendar toDate = Calendar.getInstance();
    	fromDate.setTime(jdcTo.getDate());
    	Date endDate = fromDate.getTime();
    	
    	DatabaseManager db = new DatabaseManager();
    	List<db.entity.Activitylog> activityLS = db.listActivityLog(startDate, endDate);

    	ArrayList<ActivityBean> beanLS = new ArrayList<ActivityBean>();
    	
    	for(int i=0; i<activityLS.size(); i++)
    	{
    		db.entity.Activitylog actItem = activityLS.get(i);
    		ActivityBean bean = new ActivityBean();
    		bean.setAction(actItem.getId().getAction());
    		bean.setTime(actItem.getId().getTime());
    		bean.setUserID(actItem.getUserID());
    		bean.setComment(actItem.getComment());    		
    		
    		beanLS.add(bean);
    	}
    	
    	new ExcelExporter().generateActivityLog(beanLS);
    	
    }
    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ActivityLogFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ActivityLogFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ActivityLogFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ActivityLogFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ActivityLogFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbtDisplay;
    private javax.swing.JButton jbtSave;
    private com.toedter.calendar.JDateChooser jdcFrom;
    private com.toedter.calendar.JDateChooser jdcTo;
    // End of variables declaration
    DatabaseManager dm;
}
